package com.koron.order.maintain.service.impl;

import com.koron.bean.base.Response;
import com.koron.bean.standard.jobStock.maintain.dto.MaintainDTO;
import com.koron.bean.standard.jobStock.maintain.dto.MaintainItemDTO;
import com.koron.bean.standard.jobStock.maintain.po.MaintainItemParams;
import com.koron.common.core.util.CodeTools;
import com.koron.order.common.bean.po.OrderExecute;
import com.koron.order.common.bean.po.OrderExecutePart;
import com.koron.order.common.bean.po.OrderInstructionBean;
import com.koron.order.common.bean.po.OrderSignBean;
import com.koron.order.common.service.OrderExecutePartService;
import com.koron.order.common.service.OrderExecuteService;
import com.koron.order.common.service.OrderInstructionService;
import com.koron.order.common.service.OrderSignService;
import com.koron.order.maintain.bean.convertor.MaintainConvertor;
import com.koron.order.maintain.bean.entity.*;
import com.koron.order.maintain.bean.vo.*;
import com.koron.order.maintain.feign.MaintainStandService;
import com.koron.order.maintain.service.*;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.koron.ebs.mybatis.TaskAnnotation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName MaintainExecuteServiceImpl
 * @description
 * @Author zhouj
 * @Date 2021/9/16 8:53
 */
@Service("maintainExecuteService")
public class MaintainExecuteServiceImpl implements MaintainExecuteService {

    @Autowired
    private OrderExecuteService orderExecuteService;

    @Autowired
    private OrderExecutePartService orderExecutePartService;

    @Autowired
    private MaintainReadyService maintainReadyService;

    @Autowired
    private MaintainEquipmentService equipmentService;

    @Autowired
    private MaintainItemService itemService;

    @Autowired
    private MaintainItemParamsService itemParamsService;

    @Autowired
    private MaintainService maintainService;

    @Autowired
    MaintainConvertor maintainConvertor;

    @Autowired
    OrderSignService orderSignService;

    @Autowired
    private OrderInstructionService orderInstructionService;

    @Autowired
    MaintainStandService maintainStandService;

    @Override
    @TaskAnnotation("insertOrUpdate")
    public int insertOrUpdate(SessionFactory factory, MaintainExecuteVo executeVo) {

        String orderId = executeVo.getOrderId();

        List<OrderExecute> orderExecuteList = new ArrayList<>();
        List<OrderExecutePart> orderExecutePartList = new ArrayList<>();
        List<MaintainReadyPo> maintainReadyPoList = new ArrayList<>();

        //1.作业表单信息
        OperateFormVo operateFormVo = executeVo.getOperateFormVo();

        if (operateFormVo != null) {
            insertOrUpdateOperateForm(factory, operateFormVo);
        }

        //2.正常维护执行信息
        List<MaintainExecuteInfoVo> maintainExecuteInfoVos = executeVo.getMaintainExecuteInfoVos();

        maintainExecuteInfoVos.forEach(p -> {

            //2.1工单执行信息
            OrderExecute orderExecute = new OrderExecute();
            String executeId = StringUtils.isEmpty(orderExecute.getId()) ? CodeTools.getCode32() : orderExecute.getId();
            orderExecute.setId(executeId);
            orderExecute.setOrderId(orderId);
            orderExecuteList.add(orderExecute);

            //2.2工单执行备件信息
            List<OrderExecutePart> orderExecutePart = p.getOrderExecutePart();
            if (!CollectionUtils.isEmpty(orderExecutePart)) {
                orderExecutePart.forEach(e -> {
                    e.setExecuteId(executeId);
                    e.setOrderId(orderId);
                });
                orderExecutePartList.addAll(p.getOrderExecutePart());
            }

        });

        orderExecuteService.insertBatch(factory, orderExecuteList);
        orderExecutePartService.insertBatch(factory, orderExecutePartList);

        return 1;
    }

    @Override
    @TaskAnnotation("insertOrUpdateExecuteInfo")
    public String insertOrUpdateExecuteInfo(SessionFactory factory, MaintainExecuteInfoVo maintainExecuteInfoVo) {

        //转换成工单执行信息
        OrderExecute orderExecute = maintainConvertor.voToOrderExecuteVo(maintainExecuteInfoVo);

        String orderExecuteId = orderExecute.getId();
        String orderId = orderExecute.getOrderId();

        if (StringUtils.isEmpty(orderExecuteId)) {
            orderExecute.setId(CodeTools.getCode32());
            orderExecuteService.insert(factory, orderExecute);
        } else {
            orderExecuteService.update(factory, orderExecute);
        }

        //工单执行备件信息
        List<OrderExecutePart> orderExecutePart = maintainExecuteInfoVo.getOrderExecutePart();
        orderExecutePart.forEach(p -> {
            p.setExecuteId(orderExecute.getId());
            p.setOrderId(orderId);
        });

        orderExecutePartService.insertBatch(factory, orderExecutePart);

        return orderExecuteId;
    }

    @Override
    public boolean deleteExecuteInfo(SessionFactory factory, String orderId, String orderExecuteId) {

        //根据工单id及工单执行id 删除执行信息
        orderExecuteService.deleteOrderExecute(factory, orderId, orderExecuteId);

        orderExecutePartService.deleteOrderExecutePart(factory, orderId, orderExecuteId);

        return true;
    }

    @Override
    @TaskAnnotation("insertOrUpdateOperateForm")
    public String insertOrUpdateOperateForm(SessionFactory factory, OperateFormVo operateFormVo) {

        List<MaintainReadyPo> maintainReadyPoList = operateFormVo.getMaintainReadyPoList();

        if (CollectionUtils.isEmpty(maintainReadyPoList)) {
            return null;
        }
        String maintainId = maintainReadyPoList.get(0).getMaintainId();

        //1.2 作业表单-存在问题,改进建议 入主表
        String opinion = operateFormVo.getOpinion();
        String problem = operateFormVo.getProblem();

        MaintainPo maintainPo = new MaintainPo();
        maintainPo.setId(maintainId);
        maintainPo.setOpinion(opinion);
        maintainPo.setProblem(problem);
        maintainService.update(factory, maintainPo);

        //1.3 作业表单-作业准备 根据id更新确认状态值
        maintainReadyService.updateBatch(factory, maintainReadyPoList);

        //1.4 项目
        List<MaintainItemVo> itemBeanVoList = operateFormVo.getItemBeanVoList();

        if (CollectionUtils.isEmpty(itemBeanVoList)) {
            List<MaintainEquipmentVo> maintainEquipmentVoList = operateFormVo.getMaintainEquipmentVoList();
            if (CollectionUtils.isNotEmpty(maintainEquipmentVoList)) {
                itemBeanVoList = new ArrayList<>();
                for (MaintainEquipmentVo maintainEquipmentVo : maintainEquipmentVoList) {
                    String maintainEquipmentVoId = maintainEquipmentVo.getId();
                    List<MaintainItemVo> itemVos = maintainEquipmentVo.getItemVos();
                    //设备级的签名信息
                    List<OrderSignBean> orderSignBeans = maintainEquipmentVo.getOrderSignBeanList();
                    //入库设备级的备注信息
                    equipmentService.update(factory, maintainEquipmentVo);
                    //1.4.1 设备级的签名信息
                    if (CollectionUtils.isNotEmpty(orderSignBeans)) {
                        orderSignBeans.forEach(p -> {
                            p.setItemId(maintainEquipmentVoId);
                        });
                        orderSignService.insertBatch(factory, orderSignBeans);
                    }

                    if (CollectionUtils.isNotEmpty(itemVos)) {
                        itemBeanVoList.addAll(itemVos);
                    }
                }
            }
        }

        //处理一下itemBeanVoList -- 将子节点信息 平铺出来
        List<MaintainItemVo> res = new ArrayList<>();
        dealItemBeanVoList(res, itemBeanVoList);

        if (!CollectionUtils.isEmpty(res)) {
            res.forEach(p -> {

                //1.4.1 项目备注及确认信息
                MaintainItemPo maintainItemPo = maintainConvertor.voToMaintainItemBean(p);
                itemService.update(factory, maintainItemPo);

                List<MaintainItemParamsPo> itemParamsBeanList = p.getItemParamsBeanList();

                //1.4.2 项目
                if (!CollectionUtils.isEmpty(itemParamsBeanList)) {
                    itemParamsService.insertOrUpdateBatch(factory, itemParamsBeanList);
                }

            });
        }

        return maintainId;
    }

    private void dealItemBeanVoList(List<MaintainItemVo> list, List<MaintainItemVo> itemBeanVoList) {

        if (CollectionUtils.isEmpty(itemBeanVoList)) {
            return;
        }

        for (MaintainItemVo itemVo : itemBeanVoList) {

            List<MaintainItemVo> maintainItemVoList = itemVo.getMaintainItemVoList();
            itemVo.setMaintainItemVoList(null);
            list.add(itemVo);
            if (CollectionUtils.isNotEmpty(maintainItemVoList)) {
                dealItemBeanVoList(list, maintainItemVoList);
            }
        }

        return;
    }

    @Override
    @TaskAnnotation("deleteById")
    public int deleteById(SessionFactory factory, String id) {
        return 0;
    }

    @Override
    @TaskAnnotation("queryByOrderId")
    public OperateFormVo queryByOrderId(SessionFactory factory, String orderId) {

        OperateFormVo operateFormVo = new OperateFormVo();

        //1.根据工单id查询作业表单

        //1.1 作业准备
        List<MaintainReadyPo> maintainReadyPoList = maintainReadyService.queryByOrderId(factory, orderId);
        //1.2 作业过程
        List<MaintainEquipmentVo> maintainEquipmentVoList = equipmentService.queryByOrderId(factory, orderId, null);

        //1.3 作业指导书
        List<OrderInstructionBean> orderInstructionBeans = orderInstructionService.queryByBizId(factory, orderId);

        operateFormVo.setMaintainReadyPoList(maintainReadyPoList);
        operateFormVo.setMaintainEquipmentVoList(maintainEquipmentVoList);
        operateFormVo.setOrderInstructionBeanList(orderInstructionBeans);

        MaintainPo maintainPo = maintainService.queryMaintainBeanById(factory, orderId);

        operateFormVo.setOpinion(maintainPo.getOpinion());
        operateFormVo.setProblem(maintainPo.getProblem());

        return operateFormVo;

    }

    @Override
    @TaskAnnotation("queryReadyByOrderId")
    public List<MaintainReadyPo> queryReadyByOrderId(SessionFactory factory, String orderId) {
        return maintainReadyService.queryByOrderId(factory, orderId);
    }

    @Override
    @TaskAnnotation("queryInstructionByOrderId")
    public List<OrderInstructionBean> queryInstructionByOrderId(SessionFactory factory, String orderId) {
        return orderInstructionService.queryByBizId(factory, orderId);
    }

    @Override
    @TaskAnnotation("queryEquipmentVoByOrderId")
    public List<MaintainEquipmentVo> queryEquipmentVoByOrderId(SessionFactory factory, String orderId, String maintainEquipmentId) {
        return equipmentService.queryByOrderId(factory, orderId, maintainEquipmentId);
    }

    @Override
    @TaskAnnotation("queryEquipmentBeanListByOrderId")
    public List<MaintainEquipmentPo> queryEquipmentBeanListByOrderId(SessionFactory factory, String orderId) {
        MaintainEquipmentPo maintainEquipmentPo = new MaintainEquipmentPo();
        maintainEquipmentPo.setMaintainId(orderId);
        return equipmentService.queryList(factory, maintainEquipmentPo);
    }

    @Override
    @TaskAnnotation("queryMaintainItemByEqId")
    public List<MaintainItemVo> queryMaintainItemByEqId(SessionFactory factory, String orderId, String maintainEquipmentId) {
        return itemService.queryByEquipmentId(factory, orderId, maintainEquipmentId);
    }

    @Override
    @TaskAnnotation("updateMaintainReady")
    public int updateMaintainReady(SessionFactory factory, MaintainReadyPo maintainReadyPo) {
        //主要是更新确认状态
        return maintainReadyService.update(factory, maintainReadyPo);
    }

    @Override
    @TaskAnnotation("updateMaintainItemVo")
    public int updateMaintainItemVo(SessionFactory factory, MaintainItemVo maintainItemVo) {

        //设备下-维护项目
        MaintainItemPo maintainItemPo = maintainConvertor.voToMaintainItemBean(maintainItemVo);
        //主要是修改状态,备注
        itemService.update(factory, maintainItemPo);

        /*List<MaintainItemParamsBean> itemParamsBeanList = maintainItemVo.getItemParamsBeanList();
        //先删除当前项目数据记录项列表,再插入
        itemParamsService.insertBatch(factory, itemParamsBeanList);

        List<OrderSignBean> orderSignBeanList = maintainItemVo.getOrderSignBeanList();
        //先删除当前项目签名人列表,再插入
        orderSignService.insertBatch(factory, orderSignBeanList);*/

        return 1;
    }

    @Override
    @TaskAnnotation("updateMaintainEquipment")
    public int updateMaintainEquipment(SessionFactory factory, MaintainEquipmentPo maintainEquipmentPo) {

        equipmentService.update(factory, maintainEquipmentPo);
        return 1;
    }

    @Override
    @TaskAnnotation("updateMaintainItem")
    public int updateMaintainItem(SessionFactory factory, MaintainItemPo maintainItemPo) {

        //主要是修改状态,备注
        itemService.update(factory, maintainItemPo);

        return 1;
    }

    @Override
    @TaskAnnotation("updateMaintainItemParams")
    public int updateMaintainItemParams(SessionFactory factory, MaintainItemParamsPo itemParamsBean) {
        //主要更新参数值
        return itemParamsService.update(factory, itemParamsBean);
    }

    @Override
    @TaskAnnotation("insertOrderSignInfo")
    public int insertOrderSignInfo(SessionFactory factory, OrderSignBean orderSignBean) {
        //新增签名人
        return orderSignService.insert(factory, orderSignBean);
    }

    @Override
    @TaskAnnotation("deleteOrderSignInfo")
    public int deleteOrderSignInfo(SessionFactory factory, String orderSignId) {
        //删除签名人记录
        return orderSignService.deleteById(factory, orderSignId);
    }

    @TaskAnnotation("updateBatchMaintainReady")
    @Override
    public int updateBatchMaintainReady(SessionFactory factory, List<MaintainReadyPo> maintainReadyPos) {
        return maintainReadyService.updateBatch(factory, maintainReadyPos);
    }

    @TaskAnnotation("updateBatchMaintainItem")
    @Override
    public int updateBatchMaintainItem(SessionFactory factory, List<MaintainItemPo> maintainItemPos) {
        if (CollectionUtils.isEmpty(maintainItemPos)){
            return 0;
        }
        for (MaintainItemPo maintainItemPo : maintainItemPos) {
            itemService.update(factory, maintainItemPo);
        }
        return 1;
    }

    @Override
    @TaskAnnotation("updateMaintainInfo")
    public int updateMaintainInfo(SessionFactory factory, MaintainPo maintainPo) {
        //主要更新改进建议和存在问题
        return maintainService.update(factory, maintainPo);
    }

    @Override
    @TaskAnnotation("generateStand")
    public boolean generateStand(SessionFactory factory, String orderId) {

        MaintainEquipmentPo maintainEquipmentPo = new MaintainEquipmentPo();
        maintainEquipmentPo.setMaintainId(orderId);
        List<MaintainEquipmentPo> maintainEquipmentPos = equipmentService.queryList(factory, maintainEquipmentPo);

        if (CollectionUtils.isEmpty(maintainEquipmentPos)) {
            return false;
        }

        List<MaintainItemPo> maintainItems = new ArrayList<>();
        List<MaintainItemParamsPo> maintainItemParams = new ArrayList<>();

        maintainEquipmentPos.forEach(p -> {

            List<MaintainItemPo> maintainItemsTmp = new ArrayList<>();
            List<MaintainItemParamsPo> maintainItemParamsTmp = new ArrayList<>();

            String maintainId = p.getMaintainId();
            String eqid = p.getId();
            String equipmentId = p.getEquipmentId();
            String standardId = p.getStandardId();
            Response<MaintainDTO> rsp = maintainStandService.select(standardId);
            if (rsp != null && rsp.getCode() == HttpStatus.OK.value()) {
                MaintainDTO data = rsp.getData();

                dealMaintainDTOS(data, maintainItemsTmp, maintainItemParamsTmp);

                //分别入库
                //处理数据
                maintainItemsTmp.forEach(v -> {
                    v.setEquipmentId(equipmentId);
                    v.setMaintainEquipId(eqid);
                    v.setMaintainId(maintainId);
                });

                maintainItemParamsTmp.forEach(v -> {
                    v.setEquipmentId(equipmentId);
                    v.setMaintainEquipId(eqid);
                    v.setMaintainId(maintainId);
                });

                maintainItems.addAll(maintainItemsTmp);
                maintainItemParams.addAll(maintainItemParamsTmp);

            }
        });

        itemService.insertBatch(factory, maintainItems);
        itemParamsService.insertBatch(factory, maintainItemParams);

        //dealMaintainDTOS(maintainDTOS, maintainItems, maintainItemParams);

        return true;
    }

    //标准处理
    private void dealMaintainDTOS(MaintainDTO maintainDTO, List<MaintainItemPo> maintainItems, List<MaintainItemParamsPo> maintainItemParams) {
        if (maintainDTO == null) {
            return;
        }

        List<MaintainItemDTO> itemDTOs = maintainDTO.getItemDTOs();
        dealMaintainItemDTOS(null, itemDTOs, maintainItems, maintainItemParams);

    }

    //标准处理
    private void dealMaintainItemDTOS(String parentId, List<MaintainItemDTO> maintainItemDTOS, List<MaintainItemPo> maintainItems, List<MaintainItemParamsPo> maintainItemParams) {

        if (CollectionUtils.isEmpty(maintainItemDTOS)) {
            return;
        }
        maintainItemDTOS.forEach(p -> {

            MaintainItemPo maintainItem = maintainConvertor.dtoToBean(p);
            maintainItem.setId(CodeTools.getCode32());
            maintainItem.setParentId(parentId);
            maintainItems.add(maintainItem);
            List<MaintainItemParams> itemParams = p.getItemParams();
            itemParams.forEach(v -> {
                MaintainItemParamsPo itemParamsBean = maintainConvertor.beanToBean(v);
                itemParamsBean.setItemId(maintainItem.getId());
                itemParamsBean.setId(null);
                maintainItemParams.add(itemParamsBean);
            });

            List<MaintainItemDTO> children = p.getChildren();
            dealMaintainItemDTOS(maintainItem.getId(), children, maintainItems, maintainItemParams);
        });

    }

}
